//
//  ZSOAuthController.swift
//  ZSWeibo
//
//  Created by zsj1992 on 16/4/9.
//  Copyright © 2016年 ichange. All rights reserved.
//

import UIKit

import SVProgressHUD

class ZSOAuthController: UIViewController {
    
    var webView: UIWebView?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        navigationItem.leftBarButtonItem = UIBarButtonItem.creatItem( target: self, action: "back", title: "返回")
        navigationItem.rightBarButtonItem = UIBarButtonItem.creatItem( target: self, action: "fillName", title: "填充")
    }
    
    func back(){
        self.dismissViewControllerAnimated(true, completion: nil)
    }

    //在填充方法中,利用js的交互
    func fillName(){

        let fillId  = "document.getElementById('userId').value='13638364214' "
        let fillPwd  = "document.getElementById('passwd').value='z243196' "
        
        webView!.stringByEvaluatingJavaScriptFromString(fillId)
        webView!.stringByEvaluatingJavaScriptFromString(fillPwd)
    }

    override func loadView() {
        
        webView = UIWebView()
        
        webView?.delegate = self
        
        view = webView
        
        //请求授权-->请求授权
        webView!.loadRequest(NSURLRequest(URL: NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
            )!))
    }
    
}



// MARK: - 加载页面的时候,就向服务器发送了用户名和密码..还有回调地址,key等数据

extension ZSOAuthController:UIWebViewDelegate{
    
    //将要加载网页的时候调用的方法
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
    let urlString = request.URL?.absoluteString ?? ""
    
    let flag = "code="

    if (urlString.containsString(flag)){
            
            print("请求授权成功")//和新浪搭上线了
            
            let range = urlString.rangeOfString(flag)!

            
            let code = urlString.substringFromIndex(range.endIndex)

        //在外部进行调用,调用获取token的方法,有回调的闭包
        //-->使用MVVC模式后,存储数据这些内容都是交给viewModel来执行,控制器只负责和UI相关的内容
        
        ZSUserAccountViewModel.sharedUserViewModel.loadAccessToken(code, finished: { (isSuccess) -> () in
            if !isSuccess {
            SVProgressHUD.showErrorWithStatus("登录失败")
            return
            }

            //SVProgressHUD.showSuccessWithStatus("登录成功")
            //TODO: 跳转到欢迎界面
           
//            UIApplication.sharedApplication().keyWindow?.rootViewController = ZSWelcomeViewController()
            
            NSNotificationCenter.defaultCenter().postNotificationName(changeRootViewController, object: nil)
            

        })

        return false
        }
        return true
    }


}

    
    
    
    
    
    
    
    
    






